import sys
import socket
from PySide6.QtCore import Qt, Slot, QEvent
from PySide6.QtWidgets import QApplication, QWidget
from ui_main import Ui_main
import threading
import device

class MyWidget(QWidget, threading.Thread):
    def __init__(self):
        super(MyWidget, self).__init__()
        # threading.Thread.__init__(self)
        self.ui = Ui_main()
        self.ui.setupUi(self)
        self.btn_flag = False
        self.thread_run_flag = True
        # self.sock_server = 0
        # 获取本机IP
        self.hostname, self.aliaslist, self.ipaddrlist = socket.gethostbyname_ex(socket.gethostname())
        # UI默认数据
        self.ui.combo_box_ip.addItems(self.ipaddrlist)
        self.ui.edit_port.setText("30000")
        self.ui.btn_open.setText("打开")
        # 信号与槽
        self.ui.btn_open.clicked.connect(self.open_socket_server)

    def run(self):
        print("thread running.")
        while self.thread_run_flag:
            sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     # 创建一个套接字对象
            sock_server.settimeout(2)         # 设置accept()的超时事件
            sock_server.bind((self.ui.combo_box_ip.currentText(), int(self.ui.edit_port.text())))
            sock_server.listen()
            while self.thread_run_flag:
                try:
                    conn, client_ip = sock_server.accept()
                except TimeoutError:
                    print('TimeoutError: accept() timed out.')
                else:
                    print(conn, client_ip)
            sock_server.close()

    @Slot()
    def open_socket_server(self):
        """ 开sock服务器 """
        if self.btn_flag == False:
            self.btn_flag = True
            self.thread_run_flag = True
            self.ui.btn_open.setText("关闭")
            threading.Thread.__init__(self)     # 开启socket server套接字
            try:
                self.start()
            except RuntimeError:
                print("threads can only be started once")
        else:
            self.btn_flag = False
            self.ui.btn_open.setText("打开")
            self.thread_run_flag = False    # 关闭socket server线程
            self.join()                     # 等待socket server线程退出
            print("thread exit.")

if __name__ == "__main__":
    app = QApplication()
    my_widget = MyWidget()
    my_widget.show()
    sys.exit(app.exec())